package com.toolkit.util;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import javax.activation.DataHandler;
import javax.activation.DataSource;
import javax.activation.FileDataSource;
import javax.mail.*;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;
import java.io.File;
import java.util.Properties;

@Slf4j
@Component
public class EmailUtil {

    @Value("${email.user}")
    private String emailUser;
    @Value("${email.password}")
    private String emailPassword;
    @Value("${email.host}")
    private String emailHost;

    public void sendEmail(String emailAddress, String title, String content, String filePath){
        // 3、发送 TrancePort
        try {
            // 1、创建Session Properties props,Authenticator auth
            Properties props = new Properties();
            props.setProperty("mail.host", emailHost);// 发送的服务器主机地址
            props.setProperty("mail.smtp.auth", "true");// 通过服务器的认证
            props.setProperty("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
            // 设置发送邮件的邮件服务器的属性（这里使用网易的smtp服务器）
            props.setProperty("mail.smtp.port", "465");
            props.setProperty("mail.smtp.socketFactory.port", "465");
            // 需要经过授权，也就是有户名和密码的校验，这样才能通过验证（一定要有这一条）
            props.put("mail.smtp.ssl.enable", true);
            props.setProperty("mail.smtp.connectiontimeout", String.valueOf(1000*10));
            props.setProperty("mail.smtp.timeout", String.valueOf(1000*30));
            props.setProperty("mail.smtp.writetimeout", String.valueOf(1000*60));
            Authenticator auth = new Authenticator() {
                protected PasswordAuthentication getPasswordAuthentication() {
                // 封装了发件人的用户名和密码（如果是qq有个授权码，不是写qq密码）
                return new PasswordAuthentication(emailUser, emailPassword);
                }
            };
            Session session = Session.getInstance(props, auth);
            // 2、创建MimeMessage
            MimeMessage msg = new MimeMessage(session);
            // 设置发件人
            msg.setFrom(new InternetAddress(emailUser));
            // 垃圾邮件解决问题：抄送人添加自己
            // 设置收件人
            // TO收件人 CC抄送人 BCC密送
            msg.setRecipient(Message.RecipientType.TO, new InternetAddress(emailAddress));
            log.info("关联人员酒店发送的邮箱是:{}",emailAddress);
            // 设置邮件的标题
            msg.setSubject(title);
            // 创建一个Multipart对象来包含邮件内容和附件
            Multipart multipart = new MimeMultipart();
            // 创建邮件正文
            MimeBodyPart messageBodyPart = new MimeBodyPart();
            messageBodyPart.setText(content);
            multipart.addBodyPart(messageBodyPart);

            // 创建附件部分
            MimeBodyPart attachmentPart = new MimeBodyPart();
            DataSource source = new FileDataSource(filePath);
            attachmentPart.setDataHandler(new DataHandler(source));
            String[] fileStr = filePath.split(File.separator);
            attachmentPart.setFileName(fileStr[fileStr.length - 1]); // 附件文件名
            multipart.addBodyPart(attachmentPart);
            // 设置邮件的内容
            msg.setContent(multipart, "text/html;charset=utf-8");
            Transport.send(msg);
            // 关闭 ExcelWriter
        } catch (Exception e) {
            log.error("", e);
            throw new RuntimeException(e);
        }
    }
}
